//Schedule the script to run at 11 am - or at a time when client should have impressions in his account
function main() {

// Your Twilio Account SID, see: https://www.twilio.com/console
var SID = 'INSERT_TWILIO_ACCOUNT_SID';

// Your Twilio API Auth Token, see: https://www.twilio.com/console
var AUTH = 'INSERT_TWILIO_ACCOUNT_AUTHTOKEN';

// The Twilio phone number or short code, as per the Phone Numbers Dashboard
// https://www.twilio.com/console/phone-numbers/incoming
var TWILIO_SRC_PHONE_NUMBER = 'INSERT_TWILIO_SRC_PHONE_NUMBER';

//Insert recepients phone number  
var PHONE_NUMBER ='INSERT_RECEPIENT_NUMBER';  

//Insert email adress to report SMS errors  
var EMAIL_ADDRESS ='INSERT_EMAIL'; 

var noImpCamp = 0;
var listNoImpCamps = '';
var campaigns = AdWordsApp.campaigns();
var campaignsIterator = campaigns.get()


var currentAccount = AdWordsApp.currentAccount();
var accountName =   currentAccount.getName();
Logger.log(accountName);
while (campaignsIterator.hasNext()) {
var campaign = campaignsIterator.next();

var stats = campaign.getStatsFor('TODAY');

if ((stats.getImpressions() == 0)&&(campaign.isEnabled())) {

listNoImpCamps = listNoImpCamps + campaign.getName() + '<br>';

noImpCamp = noImpCamp +1;
}
 
}
//Insert recepients of email messages. Separate them with a comma
var yourEmail = 'INSERT_EMAILS';

var EMAIL_BODY= '<b>Привер, <br> <br>Забелязваме, че във Вашият акаунт '+ accountName +' няма импресии за деня във следните кампании: <br><br> <\b>' + listNoImpCamps + '<br>Може да имате проблем с метода на плащане, моля проверете го!';
var SMS_BODY ='Привер, Забелязваме, че във Вашият акаунт '+ accountName +' няма импресии за деня във следните кампании: ' + listNoImpCamps + 'Може да имате проблем с метода на плащане, моля проверете!';
if (noImpCamp > 0 )   {

MailApp.sendEmail(yourEmail,'Внимание! ' + noImpCamp + ' кампания/и нямат импресии за деня','',{htmlBody: EMAIL_BODY})

  sendTwilioSms();
}

 function sendTwilioSms(dstPhoneNumber, message) {
  var request =
      buildTwilioMessageRequest(PHONE_NUMBER, SMS_BODY);
  sendSms(request);
}

/**
 * Send an SMS message
 * @param {!SmsRequest} request The request object to send
 */
function sendSms(request) {
  var retriableErrors = [429, 500, 503];

  for (var attempts = 0; attempts < 3; attempts++) {
    var response = UrlFetchApp.fetch(request.url, request.options);
    var responseCode = response.getResponseCode();

    if (responseCode < 400 || retriableErrors.indexOf(responseCode) === -1) {
      break;
    }
    Utilities.sleep(2000 * Math.pow(2, attempts));
  }

  if (responseCode >= 400 && EMAIL_ADDRESS) {
    MailApp.sendEmail(
        EMAIL_ADDRESS, 'Error sending SMS Message from AdWords Scripts',
        response.getContentText());
  }
}

/**
 * Builds a SMS request object specific for the Twilio service.
 * @param {string} recipientPhoneNumber Destination number including country
 *     code.
 * @param {string} textMessage The message to send.
 * @return {SmsRequest}
 */
function buildTwilioMessageRequest(recipientPhoneNumber, textMessage) {
  if (!PHONE_NUMBER) {
    throw Error('No "recipientPhoneNumber" specified in call to ' +
        'buildTwilioMessageRequest. "recipientPhoneNumber" cannot be empty');
  }
  if (!EMAIL_BODY) {
    throw Error('No "textMessage" specified in call to ' +
        'buildTwilioMessageRequest. "textMessage" cannot be empty');
  }
  var twilioUri = 'https://api.twilio.com/2010-04-01/Accounts/' +
      SID + '/Messages';
  var authHeader = 'Basic ' +
      Utilities.base64Encode(
          SID + ':' + AUTH);
  var options = {
    muteHttpExceptions: true,
    method: 'POST',
    headers: {Authorization: authHeader},
    payload: {
      From: TWILIO_SRC_PHONE_NUMBER,
      To: recipientPhoneNumber,
      // Twilio only accepts up to 1600 characters
      Body: textMessage.substr(0, 1600)
    }
  };
  return {url: twilioUri, options: options};
}  
  
}

